package net.gz01.wallet.web.interceptors;


import javax.servlet.http.HttpServletRequest;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import net.gz01.wallet.common.LayuiRespon;

/**
 * 统一异常处理类,记录异常日志
 * @author 钟展峰
 *
 * 2015年8月24日
 */
public class ExceptionInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		try {
			inv.invoke();
		} catch (Exception e) {
			e.printStackTrace();
            renderWhenHasException(inv,e);
		}
	}

	/**
	 * 当发生异常时返回数据
	 * @param inv
	 */
	public void renderWhenHasException(Invocation inv,Exception e){
		Controller controller = inv.getController();
		if(isAjaxRequest(controller.getRequest())){
			LayuiRespon resp= LayuiRespon.getException();
			resp.setMsg("系统异常，请稍后再试！");
			controller.renderJson(resp);
		}else{
			controller.render("/WEB-INF/error/exception.html");
		}
	}

	private boolean isAjaxRequest(HttpServletRequest request) {
		String requestType = request.getHeader("X-Requested-With");
		if(("XMLHttpRequest").equals(requestType)){
			return true;
		}
		return false;
	}

}
